package weka;

import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ArffLoader;
import weka.clusterers.Cobweb;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import weka.core.Utils;
import weka.core.converters.ConverterUtils.DataSource;

import weka.MysqlConection;

/**
 * This example trains Cobweb incrementally on data obtained
 * from the ArffLoader.
 *
 * @author FracPete (fracpete at waikato dot ac dot nz)
 */
public class IncrementalClusterer {

    /**
     * Expects an ARFF file as first argument.
     *
     * @param args        the commandline arguments
     * @throws Exception  if something goes wrong
     */
    public static void main(String[] args) throws Exception {
        String db_host = args[0];
        String db_user = args[1];
        String db_pass = args[2];
        String db_database = args[3];
        //conecta ao banco de dados
        MysqlConection mysql = new MysqlConection(db_host, db_user, db_pass, db_database);
        //local do arquivo arff criado pelo classificabean
        String arquivoArff = "/tmp/scientianet.arff";
        //le o arquivo arff
        // load data
        ArffLoader loader = new ArffLoader();
        loader.setFile(new File(arquivoArff));
        Instances structure = loader.getStructure();

        Instances test = DataSource.read(arquivoArff);

        //define as opcoes do cobweb
        String[] options = weka.core.Utils.splitOptions("-C 0.4");

        // instancia o cobweb e constroi o cluster
        Cobweb cw = new Cobweb();
        cw.setOptions(options);
        cw.buildClusterer(structure);
        Instance current;
        while ((current = loader.getNextInstance(structure)) != null) {
            cw.updateClusterer(current);
            //System.out.print(cw.clusterInstance(current));
            //System.out.println(" - " + current);
        }
        cw.updateFinished();


        // output generated model
        //System.out.println(cw);
        //System.out.println(cw.numberOfClusters());

        //conecta ao banco de dados e exclui os dados das tabelas jos_community_groups e jos_community_groups_members
        mysql.conectar();
        mysql.query("TRUNCATE TABLE `jos_community_groups`;");
        mysql.query("TRUNCATE TABLE `jos_community_groups_members`;");

        //arrays para guardar grupos a ser inseridos no banco de dados
        ArrayList grupos = new ArrayList();
        // output predictions
        //System.out.println("# - cluster - distribution");

        //percorre as instancias para definir os grupos
        for (int i = 0; i < test.numInstances(); i++) {
            int cluster = cw.clusterInstance(test.instance(i));

            if (!grupos.contains(cluster)) {
                grupos.add(cluster);
            }

        }
        //pega a data de hoje no formato mysql
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        //System.out.println(dateFormat.format(date));

        //insere os grupos no banco de dados
        int g = 0;
        for (int i = 1; i < grupos.size(); i++) {


            g = (Integer) grupos.get(i);
            mysql.query("INSERT INTO jos_community_groups(`id`, `published`, `ownerid`, `categoryid`, `name`, `description`, `email`, `website`,  `approvals`, `avatar`, `thumb`, `created`, `params`) VALUES ( '" + g + "', '0', '0', '6', 'semelhantes " + g + "', 'scientianet agrupamento', '', '', '0', '', '', '" + dateFormat.format(date) + "', 'discussordering=0"
                    + "photopermission=0"
                    + "videopermission=0"
                    + "grouprecentphotos=6"
                    + "grouprecentvideos=6"
                    + "newmembernotification=1"
                    + "joinrequestnotification=1"
                    + "wallnotification=1"
                    + "');");
        }


        //insere os usuarios pertencentes a cada grupo no banco de dados
        for (int i = 0; i < test.numInstances(); i++) {
            Instance ins = test.instance(i);
            int cluster = cw.clusterInstance(test.instance(i));
            double[] dist = cw.distributionForInstance(test.instance(i));
            //System.out.print((i + 1));
            //System.out.print(" - ");
            //System.out.print(cluster);
            //System.out.print(" - ");
            //System.out.print(ins);
            //System.out.println();
            int user_id = (int) ins.value(ins.attribute(0));
            //System.out.println(user_id);
            String q = "INSERT INTO jos_community_groups_members(`groupid`,`memberid`,`approved`,`permissions`) VALUES ( '" + cluster + "','" + user_id + "', '1', '0');";
            //System.out.println(q);
            mysql.query(q);

        }
    }
}
